package com.example.service;

import com.example.entity.Order;
import com.example.entity.OrderSort;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.AsyncRabbitTemplate;
import org.springframework.amqp.rabbit.RabbitConverterFuture;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AsyncOrderService {
    
    @Autowired
    private AsyncRabbitTemplate asyncRabbitTemplate;
    
    @Autowired
    private ObjectMapper objectMapper;



    /**
     * 异步发送订单并等待回复
     */
    public CompletableFuture<String> sendOrderAsync(Order order) {
        try {
            // 将订单对象转换为JSON字符串

            // 异步发送消息并返回ListenableFuture
            RabbitConverterFuture<String> future = asyncRabbitTemplate.convertSendAndReceive(
                "order.async.exchange",
                "order.async",
                    order

            );
            
            log.info("异步发送订单消息: {}", order.getId());

            // 直接使用 future 的回调处理
            return future.whenComplete((result, throwable) -> {
                if (throwable != null) {
                    log.error("处理订单失败: {}", order.getId(), throwable);
                } else {
                    log.info("收到回复: {}", result);
                }
            }).thenApply(result -> (String) result); // 如果类型匹配，这一步可能不需要

        } catch (Exception e) {
            log.error("发送订单消息失败: {}", order.getId(), e);
            CompletableFuture<String> failedFuture = new CompletableFuture<>();
            failedFuture.completeExceptionally(e);
            return failedFuture;
        }
    }
    
    /**
     * 批量异步发送订单
     */
    public List<CompletableFuture<String>> sendOrdersBatchAsync(List<Order> orders) {
        return orders.stream()
                .map(this::sendOrderAsync)
                .collect(Collectors.toList());
    }
    
    /**
     * 异步发送不等待回复
     */
    /**
     * 异步发送不等待回复
     */
    public void sendOrderNoReplyAsync(Order order) {
        try {

            // 直接发送消息，不等待回复
            asyncRabbitTemplate.convertSendAndReceive(
                    "order.async.exchange",
                    "order.async",
                    order
            ).whenComplete((result, throwable) -> {
                if (throwable != null) {
                    log.error("订单通知发送失败: {}", order.getId(), throwable);
                } else {
                    log.info("订单通知发送成功: {}", order.getId());
                }
            });

        } catch (Exception e) {
            log.error("发送订单通知失败: {}", order.getId(), e);
        }
    }
}
